import os
import psutil
import socket
import threading
from apscheduler.schedulers.blocking import BlockingScheduler


class TPServer(object):
    def __init__(self):
        super(TPServer, self).__init__()


    def get_ip(self,prefix):
        """
        通过给定前缀跨平台查询ip
        :param prefix:
        :return:
        """
        localIP = ''
        dic = psutil.net_if_addrs()
        for adapter in dic:
            snicList = dic[adapter]
            for snic in snicList:
                if not snic.family.name.startswith('AF_INET'):
                    continue
                ip = snic.address
                if ip.startswith(prefix):
                    localIP = ip
        return localIP


    def runServer(self,port,buffer):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host=self.get_ip('192.168.1.')
        print(host)
        sock.bind((host, port))
        sock.listen(10)
        print('servering listening')
        while True:
            try:
                client_sock, client_addr = sock.accept()
                recv = client_sock.recv(buffer)
                # print(chardet.detect(recv))
                # print(recv)
                if recv:
                    data = eval(recv)
                    print(data)
                    if data['ask']==1:
                        client_sock.send('on'.encode('utf-8'))#.encode('utf-8')

            except Exception as runServer_ERR:
                print(str(runServer_ERR))

def tps_server():
    PORT = 2023
    BUFFER = 1024
    tps = TPServer()
    tps.runServer(PORT, BUFFER)


def show_window():
    cmd='python3 /Applications/timeaxis_my_task/MyTask/TaskProgress/taskprogress.py'
    os.system(cmd)

scheduler = BlockingScheduler()
scheduler.add_job(show_window, 'interval', seconds=600)
try:
    tps_thread=threading.Thread(target=tps_server)
    tps_thread.start()
    scheduler.start()

except (KeyboardInterrupt, SystemExit):
    pass
